import {toast} from '../../../components/GlobalToast';
import {createGroup} from '../services/eduService';
import {Actions} from 'react-native-router-flux';

const defaultState = {
	groupIcon: undefined,
	groupIconFile: undefined,
	groupName: '',
	groupType: 0,
	groupDescription: '',
	groupPassword: undefined,
};

export default {

	namespace: 'groupCreate',
	
	state: {...defaultState},
	
	reducers: {
		
		reset() {
			return {...defaultState};
		},
		
		changeGroupIcon(state, {payload}) {
			return {...state, ...{groupIcon: payload}};
		},
		
		changeGroupIconFile(state, {payload}) {
			return {...state, ...{groupIconFile: payload}};
		},
		
		changeGroupName(state, {payload}) {
			return {...state, ...{groupName: payload}};
		},
		
		changeGroupType(state, {payload}) {
			return {...state, ...{groupType: payload}};
		},
		
		changeGroupDescription(state, {payload}) {
			return {...state, ...{groupDescription: payload}};
		},
		
	},
	
	effects: {
		
		*createGroup(action, {put, select}) {
			let createGroupState = yield select((state) => state.createGroup);
			let groupIcon = createGroupState.groupIcon;
			let groupIconFile = createGroupState.groupIconFile;
			let groupName = createGroupState.groupName;
			let groupType = createGroupState.groupType;
			let groupDescription = createGroupState.groupDescription;
			let groupPassword = createGroupState.groupPassword;
			if(!groupName) {
				return toast.show('请输入群名称');
			}
			if(!groupDescription) {
				return toast.show('请输入群描述');
			}
			if(groupIconFile) {
				let fileInfo = groupIconFile.file;
				let blob = base64ToBlob(groupIconFile.url, fileInfo.type);
				let res = yield upload(blob, fileInfo.name);
				if(res.res == 1) {
					let files = res.data;
					groupIcon = {
						fileId: files[0].fileId,
						url: files[0].fileThumbnailUrl,
					}
					yield put({type: 'changeGroupIcon', payload: groupIcon});
				} else {
					return toast.show(res.msg);
				}
			}
			let res = yield createGroup(groupIcon.fileId, groupName, groupDescription, groupType, groupPassword);
			if(res.res == 1) {
				toast.show('创建成功');
				Actions.pop();
			} else {
				toast.show(res.msg);
			}
		}
		
	},
	
}